using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class TimerUtil : SingletonMono<TimerUtil>
{
    public TextMeshProUGUI text;
    private IDisposable _disposable;
    private bool _isTimerActive;

    public void OpenTimer(Action action, int count = 5)
    {
        if (_disposable != null)
        {
            _disposable.Dispose();
            _disposable = null;
        }

        if (_isTimerActive) return;
        _isTimerActive = true;

        text.gameObject.SetActive(true);
        text.text = count.ToString();

        _disposable = Observable.Interval(TimeSpan.FromSeconds(1))
            .Take(count)
            .Subscribe(x =>
            {
                Debug.Log($"x:{x}");
                int remain = count - (int)(x + 1);
                text.text = remain.ToString();
            }, () =>
            {
                action?.Invoke();
                _isTimerActive = false;
                text.gameObject.SetActive(false);
            });
    }
}
